<?php

use Illuminate\Database\Capsule\Manager as DB;

#[区域经销商管理]
class QudaiController extends AcommonController
{
    public function init() {
        $this->model = (new qudaiModel());
        $this->table = 'qudai';
        $this->primaryKey = 'qudai_id';
        parent::init();
    }

    #[经销商列表]
    public function indexAction($returnData = FALSE)
    {
        $this->model = $this->model->with(['member', 'qudai_last_log', 'qudai_level']);
        if($this->isPost()) {
            $startOn = $this->get('start_on');
            if (!empty($startOn)) {
                $this->model = $this->model->whereDate('created_at','>=', $startOn);
            }
            $endOn = $this->get('end_on');
            if (!empty($endOn)) {
                $this->model = $this->model->whereDate('created_at','<=', $endOn);
            }
            $level = $this->get('level');
            if($level){
                $this->model = $this->model->where('area_level', $level);
            }
            $type     = $this->get('keywordsType');
            $keywords = $this->get('keywords');
            if ($keywords) {
                switch ($type){
                    case 'user_id';
                        array_push($this->search, ['qudai_id', '=', $keywords]);
                        break;
                    case 'user_phone':
                        array_push($this->condition_in, ['qudai_id', memberModel::query()->where('phone', 'like', "%{$keywords}%")->pluck('id')->toArray()]);
                        break;
                    case 'company_name';
                        array_push($this->search, ['company_name', 'like', "%{$keywords}%"]);
                        break;
                }
            }
            return parent::indexAction(false);
        }else{
            $level_list = [];
            $levelModel = qudailevelModel::query()->select('level', 'name')->orderBy('level', 'ASC')->get();
            if($levelModel){
                $level_list = $levelModel->toArray();
            }
            $this->_view->assign('level_list', json_encode($level_list, JSON_UNESCAPED_UNICODE));
            $this->_view->display( strtolower($this->controller) . '/index.html');
        }
    }

    #[经销商分红设置]
    public function configAction(){
        if($this->isPost()){
            $postData = $this->postData;
            if (isset($postData['usable_status'])){
                configModel::query()->updateOrInsert(['type'=>19,'key'=>'qudai'],['value'=>$postData['usable_status'],'updated_at'=>date('Y-m-d H:i:s')]);
            }
            if(isset($postData['bonus_rules']) && is_array($postData['bonus_rules']) && count($postData['bonus_rules'])){
                foreach ($postData['bonus_rules'] as $v) {
                    $int_level = intval($v['level']);
                    if($int_level && is_numeric($v['commission_rules'])){
                        if((round(floatval($v['commission_rules']), 3) > round(100, 3)) || (round(floatval($v['commission_rules']), 3) < round(0.01, 3))){
                            $commission_rules = 0;
                        }else{
                            $commission_rules = $v['commission_rules'];
                        }
                        qudailevelModel::query()->where('level', $v['level'])->update(['commission_rules'=>$commission_rules]);
                    }
                    if($int_level && is_numeric($v['enbale_goods_id'])){
                        $enbale_goods_id = 0;
                        if($v['enbale_goods_id'] > 0 && goodsModel::query()->where('id', $v['enbale_goods_id'])->exists()){
                            $enbale_goods_id = $v['enbale_goods_id'];
                        }
                        qudailevelModel::query()->where('level', $v['level'])->update(['enbale_goods_id'=>$enbale_goods_id]);
                    }
                }
                unset($int_level);
                unset($v);
            }
            ret(0, '区域经销商分红设置更新成功！');
        }else{
            $open_status = configModel::query()->where([['type', 19],['key', 'qudai']])->value('value');
            $configs_arr = qudailevelModel::query()->orderBy('level', 'ASC')->select(['level', 'name', 'commission_rules', 'enbale_goods_id'])->get()->toArray();
            $config = [
                'usable_status' => $open_status,
                'bonus_rules' => $configs_arr,
            ];
            $this->_view->assign('dataset', json_encode($config, JSON_UNESCAPED_UNICODE));
            $this->_view->display( strtolower($this->controller) . '/config.html');
        }
    }

    #[退出经销商]
    public function deleteAction()
    {
        do {
            $del_id = $this->getPost('id', '0');
            $del_remark = $this->getPost('remark', '管理员删除区域经销商');
            if (empty($del_id)) {
                $result = [
                    'ret' => 2,
                    'msg' => '参数为空',
                ];
                break;
            } elseif (is_numeric($del_id)) {
                if (DB::table($this->table)->where($this->primaryKey, '=', $del_id)->doesntExist()) {
                    $result = [
                        'ret' => 4,
                        'msg' => '记录不存在',
                    ];
                    break;
                }
                if (DB::table($this->table)->where($this->primaryKey, '=', $del_id)->delete()) {
                    DB::table('qudai_log')->insert([
                        'qudai_id'  =>  $del_id,
                        'event'      =>  'signout',
                        'event_id'   =>  0,
                        'remark'     =>  $del_remark,
                        'oper_type'  =>  'admin',
                        'oper_id'    =>  $this->auth->user_id,
                        'created_at' =>  date('Y-m-d H:i:s'),
                    ]);
                    $result = [
                        'ret' => 0,
                        'msg' => '删除操作成功！',
                    ];
                    break;
                }
            }
            $result = [
                'ret' => '5',
                'msg' => '删除失败',
            ];
        } while (FALSE);
        json($result);
    }

    #[经销商分红记录]
    public function rewardAction(){
        if($this->isPost()){
            $params = $this->postData;
            $page = $params['page'] ?? 1;
            $per_page = $params['rows'] ?? 10;

            $rewardModel = (new qudairewardModel())->newQuery();
            $query = $rewardModel->with(['qudai','buyerInfo','orderInfo','orderItemInfo', 'qudaiLevelInfo'])->orderByDesc('created_at');
            if(isset($params['mode']) && $params['mode'] != 'all'){
                switch ($params['mode']){
                    case 'waiting':
                        $query = $query->where('status', qudairewardModel::COMMISSION_REWARD_STATUS_WAITING);
                        break;
                    case 'accounted':
                        $query = $query->where('status', qudairewardModel::COMMISSION_REWARD_STATUS_ACCOUNTED);
                        break;
                    case 'cancel':
                        $query = $query->where('status', qudairewardModel::COMMISSION_REWARD_STATUS_CANCEL);
                        break;
                    case 'back':
                        $query = $query->where('status', qudairewardModel::COMMISSION_REWARD_STATUS_BACK);
                        break;
                }
            }
            if(isset($params['start_on']) && !empty($params['start_on'])){
                $query= $query->whereDate('created_at','>=', $params['start_on']);
            }
            if(isset($params['end_on']) && !empty($params['end_on'])){
                $query= $query->whereDate('created_at', '<=', $params['end_on']);
            }
            if(isset($params['keywords']) && !empty($params['keywords'])){
                if(isset($params['keywordsType']) && !empty($params['keywordsType'])){
                    switch ($params['keywordsType']){
                        case 'qudai_id':
                            $query = $query->where('qudai_id', $params['keywords']);
                            break;
                        case 'qudai_phone':
                            $query = $query->whereIn('qudai_id', memberModel::query()->where('phone', 'like', "%{$params['keywords']}%")->pluck('id')->toArray());
                            break;
                        case 'order_id':
                            $query = $query->where('order_id', $params['keywords']);
                            break;
                        case 'order_sn':
                            $query = $query->whereIn('order_id', orderModel::query()->where('order_sn', 'like', "%{$params['keywords']}%")->pluck('id')->toArray());
                            break;
                        case 'buyer_id':
                            $query = $query->where('buyer_id', $params['keywords']);
                            break;
                        case 'buyer_phone':
                            $query = $query->whereIn('buyer_id', memberModel::query()->where('phone', 'like', "%{$params['keywords']}%")->pluck('id')->toArray());
                            break;
                        case 'goods_id':
                            $query = $query->whereIn('order_item_id', orderitemModel::query()->where('goods_id', $params['keywords'])->pluck('id')->toArray());
                            break;
                        case 'goods_title':
                            $query = $query->whereIn('order_item_id', orderitemModel::query()->where('goods_title', 'like', "%{$params['keywords']}%")->pluck('id')->toArray());
                            break;
                    }
                }
            }
            $total = $query->count();
            if(isset($params['sort'])){
                $query = $query->orderBy($params['sort']?:'id', (isset($params['order'])&&in_array($params['order'],['asc','desc']))?$params['order']:'desc');
            }
            $data = $query->offset(($page - 1) * $per_page)
                ->limit($per_page)
                ->get()->toArray();
            json([
                'total' => $total,
                'rows'=>$data
            ]);
        }else{
            $this->_view->display( strtolower($this->controller) . '/reward.html');
        }
    }

    #[经销商详情]
    public function infoAction()
    {
        $has_flag = !1;
        $qudai_id = $this->get('id');
        $data = [];
        if($qudai_id){
            if($this->model->where('qudai_id', $qudai_id)->exists()){
                $has_flag = !0;
                $data = $this->model->with(['member', 'qudai_log', 'qudai_level'])->where('qudai_id', $qudai_id)->first()->toArray();
            }
        }
        $this->_view->assign('has_flag', $has_flag);
        $this->_view->assign('dataset', json_encode($data, JSON_UNESCAPED_UNICODE));
        $this->_view->display( strtolower($this->controller) . '/info.html');
    }

    #[经销商分红明细]
    public function singlerewardAction()
    {
        $qudai_id = $this->get('id');
        if($this->isPost()){
            if($qudai_id && $this->model->where('qudai_id', $qudai_id)->exists()){
                $query = qudairewardModel::query()->with(['orderInfo', 'qudaiLevelInfo'])->where('qudai_id', $qudai_id);
                $total = $query->count();
                $query = $query->orderByDesc('created_at');
                $page = $this->get('page', 1);
                $limit = $this->get('rows', 10);
                $offset = ($page - 1) * $limit;
                $query = $query->offset($offset)->limit($limit);
                $rows = $query->get();
                json(['total' => $total, 'rows' => $rows]);
            }else{
                json(['total' => 0, 'rows' => []]);
            }
        }else{
            $this->_view->assign('qudai_id', $qudai_id);
            $this->_view->display( strtolower($this->controller) . '/signlereward.html');
        }
    }

    #[经销商导出]
    public function exportAction()
    {
        $type     = $this->get('keywordsType');
        $keywords = $this->get('keywords');
        $startOn = $this->get('start_on');
        $endOn = $this->get('end_on');
        $level = $this->get('level');

        $dirpath = APP_PATH . '/public/excel/';
        if ($dirpath !== '.' && !file_exists($dirpath)) {
            mkdir($dirpath, 0777, true);
        }
        $filename = 'regionalDistributors' . date('Ymd') . uniqid() . '.xlsx';
        $filepath = $dirpath . $filename;
        $res = exec("php ". APP_PATH . "/public/cli.php export/qudai \"type={$type}&keywords={$keywords}&level={$level}&start_on={$startOn}&end_on={$endOn}&path={$filepath}\"");
        if ($res === 'Done' && file_exists($dirpath . $filename)) {
			if( $webpath = syncFile($filepath) ){
                ret(0, '经销商导出excel成功', $webpath);
            }
        }
        ret(30003, '经销商导出失败');
    }

    #[经销商分拥记录导出]
    public function rewardexportAction()
    {
        $type     = $this->get('keywordsType');
        $keywords = $this->get('keywords');
        $startOn = $this->get('start_on');
        $endOn = $this->get('end_on');
        $mode = $this->get('mode');

        $dirpath = APP_PATH . '/public/excel/';
        if ($dirpath !== '.' && !file_exists($dirpath)) {
            mkdir($dirpath, 0777, true);
        }
        $filename = 'regionalDistributorsReward' . date('Ymd') . uniqid() . '.xlsx';
        $filepath = $dirpath . $filename;
        $res = exec("php ". APP_PATH . "/public/cli.php export/qudaireward \"mode={$mode}&type={$type}&keywords={$keywords}&start_on={$startOn}&end_on={$endOn}&path={$filepath}\"");
        if ($res === 'Done' && file_exists($dirpath . $filename)) {
			if( $webpath = syncFile($filepath) ){
                ret(0, '经销商分红记录导出excel成功', $webpath);
            }
        }
        ret(30003, '经销商分红记录导出失败');
    }
}